﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RegexParser
{
	/// <summary>
	/// Categorized pieces of a regular expression.
	/// </summary>
	public class RegexToken
	{
		public enum Categories
		{
			OrdinaryCharacter,
			Character,
			Assertion,
			Quantifier,
			Grouping,
			Backreference,
			Alternation,
			Comment,
			Invalid
		}

		private void GetFullPattern(List<RegexToken> MyTokens)
		{
			foreach (var t in MyTokens)
			{
				_FullPattern += t.Pattern;
				if (t.Tokens.Count > 0) GetFullPattern(t.Tokens);
			}
		}

		private string _FullPattern;
		/// <summary>
		/// Crawl this token and all its children to obtain the full pattern of this node.
		/// </summary>
		public string FullPattern
		{
			get
			{
				if (_FullPattern == null)
				{
					_FullPattern = Pattern;
					GetFullPattern(Tokens);
				}
				return _FullPattern;
			}
		}

		public string Pattern;
		public Categories Category;
		public int Position;
		public RegexToken Parent;
		private List<RegexToken> _Tokens;
		public List<RegexToken> Tokens // using lazy loading here is 16% faster than initializing in the constructor
		{
			get
			{
				if (_Tokens == null)
					_Tokens = new List<RegexToken>();
				return _Tokens;
			}
		}

		public bool TokensEmpty
		{
			get
			{
				return _Tokens == null || _Tokens.Count == 0;
			}
		}

		public RegexToken(string pattern, int position, Categories category)
		{
			Pattern = pattern;
			Category = category;
			Position = position;
		}

		public RegexToken(RegexToken parent, string pattern, int position, Categories category)
		{
			Parent = parent;
			Pattern = pattern;
			Category = category;
			Position = position;
		}
	}
}
